from django.http import JsonResponse
from common.models import Medicine
from lib.handler import dispatcherBase
from django.core.paginator import Paginator, EmptyPage
from django.db.models import Q


# api接口1.2，list_medicine
def list_medicine(request):
    qs = Medicine.objects.values() # 获取所有记录
    pagesize = request.params['pagesize'] # 请求消息中给出的每页的记录条数
    pagenum = request.params['pagenum'] # 请求获取第几页信息
    keywords = request.params.get('keywords')
    if keywords:
        keywords_list = keywords.split()
        query = Q()
        for k in keywords_list:
            query |= Q(name__contains=k)
        qs = qs.filter(query)

    # 使用分页对象，根据请求指定的每页记录条数进行分页
    pgnt = Paginator(qs, pagesize)
    # 从调用分页对象的get_page方法读取请求的页数
    page = pgnt.get_page(pagenum)
    # 将读取的信息转列表
    retlist = list(page)
    return JsonResponse({'ret': 0, 'retlist': retlist, 'total': pgnt.count})


def add_medicine(request):
    info = request.params['data']
    record = Medicine.objects.create(
        name = info['name'],
        sn = info['sn'],
        desc = info['desc']
    )
    return JsonResponse({'ret': 0, 'msg': record.id})

def modify_medicine(request):
    medicineid = request.params['id']
    newdata = request.params['newdata']
    try:
        medicine = Medicine.objects.get(id=medicineid)
    except Medicine.DoesNotExist:
        return JsonResponse({'ret': 1, 'msg': f'id为{medicineid}的药品不存在'})
    if 'name' in newdata:
        medicine.name = newdata['name']
    if 'sn' in newdata:
        medicine.sn = newdata['sn']
    if 'desc' in newdata:
        medicine.desc = newdata['desc']
    medicine.save()
    return JsonResponse({'ret': 0})

def del_customer(request):
    medicineid = request.params['id']
    try:
        medicine = Medicine.objects.get(id=medicineid)
    except Medicine.DoesNotExist:
        return JsonResponse({'ret': 1, 'msg': f'id为{medicineid}的药品不存在'})
    medicine.delete()
    return JsonResponse({'ret': 0})

action_handler_dict = {
    'list_medicine': list_medicine,
    'add_medicine': add_medicine,
    'modify_medicine': modify_medicine,
    'del_customer': del_customer,
}

def dispatcher(request):
    return dispatcherBase(request, action_handler_dict)